package com.ftp.web.spider.service.nettyserver;

import com.ftp.web.spider.service.nettyserver.NettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/***
 * 文件传输接收类
 */
@Component
public class NettyServer implements ApplicationRunner {


    private EventLoopGroup mastLoopGroup=new NioEventLoopGroup();
    private EventLoopGroup selvLoopGroup=new NioEventLoopGroup();


    private ServerBootstrap serverBootstrap=new ServerBootstrap();



    private Integer port=9090;

    public void openNettyServer() throws InterruptedException {
        ChannelFuture future=serverBootstrap.group(mastLoopGroup,selvLoopGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,124)
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addLast(new ObjectEncoder());
                        channel.pipeline().addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.weakCachingResolver(null)));
                        channel.pipeline().addLast(new NettyServerHandler());
                    }
                })
                .bind(port)
                .sync();
        if(future.isSuccess()){
            System.out.println("通道开启成功");
        }else {
            System.out.println("通道开启失败");
        }
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        this.openNettyServer();
        System.out.println("自启动");
    }
}
